﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;

namespace ConsoleApplication1
{
    class Program
    {
        static string FiltersText
        {
            get
            {
                return 
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n" +
                "    <ItemGroup>\n" +
                "        <Filter Include=\"源文件\">\n" +
                "            "+GetUniqueIdentifier()+"\n"+
                "            <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n" +
                "        </Filter>\n" +
                "        <Filter Include=\"头文件\">\n" +
                "           "+GetUniqueIdentifier() + "\n" +
                "             <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>\n" +
                "        </Filter>\n" +
                "        <Filter Include=\"资源文件\">\n" +
                "           "+GetUniqueIdentifier() + "\n" +
                "            <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n" +
                "        </Filter>";
            }
        }

        static string GetUniqueIdentifier()
        {
            return string.Format("<UniqueIdentifier>{{{0}}}</UniqueIdentifier>", Guid.NewGuid().ToString());
        }

        static string GetPathNode(string pathname)
        {
            return string.Format("<Filter Include=\"{0}\">{1}</Filter>\n", pathname, GetUniqueIdentifier());
        }

        static void Main(string[] args)
        {
            args = new string[3]
            {
                "E:\\source code\\mudos\\code\\mudos-mysql\\WinDebug\\Bin\\mudlib.vcxproj", 
                "E:\\source code\\mudos\\code\\mudos-mysql\\WinDebug\\Bin\\mudlib.vcxproj.filters", 
                "E:\\source code\\mudos\\code\\mudos-mysql\\WinDebug\\Bin\\" 
            };

            if (args.Length != 3)
            {
                Console.WriteLine("请配置所要修改的文件名！按任意键结束!");
                Console.ReadKey();
                return;
            }

            // 读取要修改的工程文件内容
            Char[] textChars = null;
            int begin = 0, end = 0;
            {
                sdfsdfsdf.LoadXMLFile(args[0]);
                FileInfo fileInfo = new FileInfo(args[0]);
                StreamReader reader = fileInfo.OpenText();
                if (reader == null)
                {
                    Console.WriteLine("所要修改的配置文件不存在！按任意键结束!");
                    Console.ReadKey();
                    return;
                }
                
                textChars = new Char[fileInfo.Length];
                reader.Read(textChars, 0, (int)fileInfo.Length);

                begin = FindChar(textChars, "<ItemGroup>", 0) + "<ItemGroup>".Length;
                if (begin == -1)
                {
                    begin = FindChar(textChars, "</Project>", 0);
                    end = begin;
                }
                else
                {
                    end = FindChar(textChars, "</ItemGroup>", begin);
                }

                reader.Close();
            }

            string path = args[2];
            Console.WriteLine(path);

            // 得到目录下的所有文件
            List<string> resultList = new List<string>();
            {
                string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
                foreach (string file in files)
                {
                    if (file.Contains(".svn"))
                        continue;

                    resultList.Add(file.Replace(path, ""));
                    Console.WriteLine(resultList[resultList.Count - 1]);
                }
            }

            string vcxprojText = new string(textChars, 0, begin);
            string vcxprojFiltersText = FiltersText; // 先查找所有目录
            Dictionary<string, bool> exiList = new Dictionary<string, bool>();
            vcxprojFiltersText += "\n";
            for (int i = 0; i < resultList.Count; ++i)
            {
                string[] names = SplitFile(resultList[i]);
                if (!string.IsNullOrEmpty(names[0]))
                {
                    string sspath = "";
                    string[] layers = names[0].Split('\\');
                    for (int m = 0; m < layers.Length; ++m)
                    {
                        sspath += string.Format("\\{0}", layers[m]);
                        if (!exiList.ContainsKey(sspath))
                        {
                            exiList.Add(sspath, true);
                            vcxprojFiltersText += GetPathNode(sspath.Substring(1));
                        }
                    }
                }
            }
            vcxprojFiltersText += "\n</ItemGroup>\n<ItemGroup>\n";

            for (int i = 0; i < resultList.Count; ++i)
            {
                string[] names = SplitFile(resultList[i]);
                if (!string.IsNullOrEmpty(names[0]))
                {
                    vcxprojFiltersText += string.Format("<ClInclude Include=\"{0}\">\n<Filter>{1}</Filter>\n</ClInclude>\n", names[1], names[0]);
                }
                vcxprojText += string.Format("<ClInclude Include=\"{0}\" />\n", resultList[i]);
            }

            vcxprojText += new string(textChars, end, textChars.Length-end-1);
            vcxprojFiltersText += "</ItemGroup>\n</Project>";

            // 重新写回文件当中
            WriteToFile(args[0], vcxprojText);
            WriteToFile(args[1], vcxprojFiltersText);
            Console.ReadKey();
        }

        static void WriteToFile(string file, string text)
        {
            File.Delete(file + ".bak");
            File.Copy(file, file + ".bak");
            File.Delete(file);
            File.WriteAllText(file, text, Encoding.UTF8);
        }

        static string[] SplitFile(string file)
        {
            int index = file.LastIndexOf('\\');
            if (index == -1)
            {
                return new string[2] { "", file };
            }
            else
            {
                return new string[2] { file.Substring(0, index), file.Substring(index+1) };
            }
        }

        static int FindChar(Char[] t, string find, int startindex)
        {
            int lenght = t.Length - find.Length;
            for (int i = 0; i < lenght; ++i)
            {
                bool bf = true;
                for (int j = 0; j < find.Length; ++j)
                {
                    if (t[i + j] != find[j])
                    {
                        bf = false;
                        break;
                    }
                }

                if (bf)
                    return i;
            }

            return -1;
        }

        static void GetPathAll(string path, ref string text)
        {

        }
    }
}
